package com.jarvis.hospital.prescription;

import android.app.Dialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jarvis.hospital.R;
import com.jarvis.hospital.SettingActivity;
import com.jarvis.hospital.common.BaseActivity;
import com.jarvis.hospital.common.ResponseData;
import com.jarvis.hospital.prescription.adapter.CFDurationAdapter;
import com.jarvis.hospital.prescription.adapter.MedicineBasicAdapter;
import com.jarvis.hospital.prescription.adapter.MedicineStockAdapter;
import com.jarvis.hospital.prescription.model.CFIntervalListModel;
import com.jarvis.hospital.prescription.model.CFIntervalModel;
import com.jarvis.hospital.prescription.model.MedicineBasicListModel;
import com.jarvis.hospital.prescription.model.MedicineBasicModel;
import com.jarvis.hospital.prescription.model.MedicineStockListModel;
import com.jarvis.hospital.prescription.model.MedicineStockModel;
import com.jarvis.hospital.servers.ApiService;
import com.jarvis.hospital.util.DividerItemDecoration;
import com.jarvis.hospital.util.net.RequestApi;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MedicineStockLogActivity extends BaseActivity {
    private ApiService service;
    @BindView(R.id.recy_medicine)
    RecyclerView recy_medicine;
    @BindView(R.id.ptr_medicine)
    PtrClassicFrameLayout ptr_medicine;
    private MedicineStockAdapter medicineStockAdapter;
    private int pageSize = 10;
    private int currentPage = 1;
    private int maxPage = 1;
    @BindView(R.id.rel_left)
    RelativeLayout rel_left;
    @BindView(R.id.rel_right)
    RelativeLayout rel_right;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_right)
    TextView tv_right;
    @BindView(R.id.tv_add)
    TextView tv_add;

    private Dialog dialog;
    private RecyclerView recycleView;
    private List<MedicineBasicModel> medicineBasicList = new ArrayList<>();
    private MedicineBasicAdapter medicineBasicAdapter;
    private MedicineBasicModel selectMedicineBasicModel;

    @Override
    public int getLayoutId() {
        return R.layout.activity_medicine_stock;
    }

    @Override
    public void initData() {
        ptr_medicine.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        ptr_medicine.autoRefresh();
                    }
                }, 100);
    }

    /**
     * 设置下拉刷新
     */
    public void setRefresh() {
        ptr_medicine.setMode(PtrFrameLayout.Mode.BOTH);
        ptr_medicine.disableWhenHorizontalMove(true);
        ptr_medicine.setLastUpdateTimeRelateObject(this);
        ptr_medicine.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return PtrDefaultHandler2.checkContentCanBePulledUp(frame, recy_medicine, footer);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler2.checkContentCanBePulledDown(frame, recy_medicine, header);
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                if (currentPage < maxPage) {
                    currentPage++;
                    loadData();
                } else {
                    ptr_medicine.refreshComplete();
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                medicineStockAdapter.setNewData(new ArrayList<MedicineStockModel>());
                currentPage = 1;
                loadData();
            }
        });
    }

    private void showAddMedicineDialog() {
        selectMedicineBasicModel=null;
        for (int j = 0; j < medicineBasicList.size(); j++) {
            MedicineBasicModel medicineBasicModel1 = medicineBasicList.get(j);
            medicineBasicModel1.setSelect(false);
        }
        LayoutInflater inflater = LayoutInflater.from(this);
        View customView = inflater.inflate(R.layout.dia_add_medicine, null);
        dialog = new Dialog(this);
        dialog.setContentView(customView);
        dialog.setCancelable(false);
        dialog.show();
        recycleView = (RecyclerView) customView.findViewById(R.id.recy);
        TextView tv = (TextView) customView.findViewById(R.id.tv_title);
        TextView tv_confirm = (TextView) customView.findViewById(R.id.tv_confirm);
        TextView tv_cancel = (TextView) customView.findViewById(R.id.tv_cancel);
        final EditText ed_value = (EditText) customView.findViewById(R.id.ed_value);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String medicineDose = ed_value.getText().toString();
                if (TextUtils.isEmpty(medicineDose)) {
                    showTextToast("请输入添加剂量");
                } else if (selectMedicineBasicModel == null) {
                    showTextToast("请选择药品名称");
                } else {
                    addMedicineStock(medicineDose);
                }
            }
        });
        tv.setText("药品数量（g）");
        setcfDurationAdapter();
    }

    public void setcfDurationAdapter() {
        medicineBasicAdapter = new MedicineBasicAdapter(R.layout.item_choose, medicineBasicList);
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        medicineBasicAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recycleView.setAdapter(medicineBasicAdapter);
        recycleView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                MedicineBasicModel medicineBasicModel = medicineBasicAdapter.getData().get(i);
                selectMedicineBasicModel = medicineBasicModel;
                for (int j = 0; j < medicineBasicList.size(); j++) {
                    MedicineBasicModel medicineBasicModel1 = medicineBasicList.get(j);
                    medicineBasicModel1.setSelect(false);
                }
                medicineBasicModel.setSelect(true);
                medicineBasicList.set(i, medicineBasicModel);
                medicineBasicAdapter.notifyDataSetChanged();
            }
        });
    }

    private void addMedicineStock(String medicineDose) {
        showDialog("加载中");
        service.addMedicineStock(selectMedicineBasicModel.getMedicineId(),selectMedicineBasicModel.getMedicineName(),medicineDose)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (responseData != null) {
                            int resultCode = responseData.getResultCode();
                            if (resultCode == 200) {
                                dialog.dismiss();
                                ptr_medicine.postDelayed(
                                        new Runnable() {
                                            @Override
                                            public void run() {
                                                ptr_medicine.autoRefresh();

                                            }
                                        }, 100);
                            } else {
                                showTextToast(responseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });
    }

    private void getMedicineBasicList() {
        showDialog("加载中");
        service.getMedicineBasicList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<MedicineBasicListModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<MedicineBasicListModel> medicineBasicListModelResponseData) {
                        if (medicineBasicListModelResponseData != null) {
                            int resultCode = medicineBasicListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                medicineBasicList = medicineBasicListModelResponseData.getData().getMedicineBasicList();
                                showAddMedicineDialog();
                            } else {
                                showTextToast(medicineBasicListModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });
    }

    private void loadData() {
        service.getMedicineStockLog(currentPage, pageSize)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<MedicineStockListModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<MedicineStockListModel> medicineStockListModelResponseData) {
                        if (medicineStockListModelResponseData != null) {
                            int resultCode = medicineStockListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                int total_count = medicineStockListModelResponseData.getTotalcount();
                                maxPage = total_count % pageSize == 0 ? total_count / pageSize : total_count / pageSize + 1;
                                medicineStockAdapter.addData(medicineStockListModelResponseData.getData().getMedicineStockLogList());
                            } else {
                                showTextToast(medicineStockListModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ptr_medicine.refreshComplete();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        ptr_medicine.refreshComplete();
                    }
                });
    }

    @Override
    public void initView() {
        service = RequestApi.create(ApiService.class);
        rel_left.setVisibility(View.GONE);
        tv_right.setText("设置");
        tv_title.setText("药品出入库记录");
        rel_right.setVisibility(View.VISIBLE);
        rel_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(SettingActivity.class);
            }
        });
        tv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (medicineBasicList.size() == 0) {
                    getMedicineBasicList();
                } else {
                    showAddMedicineDialog();
                }
            }
        });
        setAdapter();
        setRefresh();
        recy_medicine.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                medicineStockAdapter.getData().get(i);
            }
        });
    }

    /**
     * 设置adapter
     */
    public void setAdapter() {
        medicineStockAdapter = new MedicineStockAdapter(R.layout.item_medicine_stock, new ArrayList<MedicineStockModel>());
        recy_medicine.setLayoutManager(new LinearLayoutManager(this));
        recy_medicine.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        medicineStockAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recy_medicine.setAdapter(medicineStockAdapter);
    }
}
